<template>
  <a-drawer title="搭配图" :width="500" @close="currentKonvaImgVisible = false" :visible="currentKonvaImgVisible">
    <div class="img-content">
      <div class="left">
        <v-stage ref="stage" :config="stageSize" @mousedown="handleStageMouseDown" @touchstart="handleStageMouseDown">
          <v-layer ref="layer">
            <v-image v-for="item in rectangles" :config="{ ...item, ...{ image: imgObj(item) } }" :key="item.id" @transformend="handleTransformEnd" :ref="item.name" />
            <v-transformer ref="transformer" :config="transformer" />
          </v-layer>
        </v-stage>
      </div>
      <div class="right">
        <a-button type="primary" style="margin-bottom: 15px" @click="up">图层上移</a-button>
        <a-button type="primary" @click="down">图层下移</a-button>
      </div>
    </div>
    <div class="footer-wrapper">
      <a-button type="primary" @click="save">下载图片</a-button>
    </div>
  </a-drawer>
</template>

<script>
import Vue from 'vue'
import VueKonva from 'vue-konva'
Vue.use(VueKonva)
export default {
  props: {
    konvaImgVisible: {
      type: Boolean,
      default: false
    },
    createStylingList: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      // Konva start
      // createStylingList: [
      //   {
      //     colorNo: "480",
      //     height: "800",
      //     imgurl: "https://jnbyoss.oss-cn-hangzhou.aliyuncs.com/upload/20210722/73f7f6a33322c09c285795850e920180.png",
      //     productId: 621756,
      //     type: 1,
      //     width: "800"
      //   },
      //   {
      //     colorNo: "901",
      //     height: "800",
      //     imgurl: "https://jnbyoss.oss-cn-hangzhou.aliyuncs.com/upload/20210723/dbaa670755e5ca2a2d18e71d6bc89e5a.png",
      //     productId: 621849,
      //     type: 0,
      //     width: "800"
      //   }
      // ],
      stageSize: {
        width: 340,
        height: 500,
        x: 70,
        y: 0
      },
      selectedShapeName: '',
      currentName: '',
      imgList: [],
      rectangles: [],
      transformer: {
        keepRatio: true,
        enabledAnchors: ['top-left', 'top-right', 'bottom-left', 'bottom-right'],
        // 变换控件样式
        anchorStroke: 'rgba(19,117,242,1)',
        anchorFill: 'rgba(19,117,242,0.5)',
        anchorSize: 10,
        borderStroke: 'rgba(19,117,242,1)',
        borderDash: [3, 3]
      },
      canvasImg: '',
      zipImg50: '?image/auto-orient,1/quality,q_50'
      // Konva end
    }
  },
  computed: {
    currentKonvaImgVisible: {
      get() {
        return this.konvaImgVisible
      },
      set(val) {
        this.$emit('update:konvaImgVisible', val)
      }
    },
    // Konva start
    imageObj: () => {
      const image = new Image()
      image.src = 'https://img.bzhz.jnbygroup.com/stylingbg2.png'
      image.crossOrigin = 'anonymous'
      return image
    },
    imgObj: () => {
      return item => {
        const image = new Image()
        image.src = item.src
        image.crossOrigin = 'anonymous'
        return image
      }
    }
    // Konva end
  },
  watch: {
    createStylingList: function (newVal, oldVal) {
      this.init()
    }
  },
  created() {},
  mounted() {},
  methods: {
    init() {
      this.imgList = this.createStylingList.map(item => {
        return {
          imgUrl: item.imgurl,
          height: item.height,
          width: item.width,
          type: item.type
        }
      })
      this.fetchImgData()
    },
    fetchImgData() {
      const top = this.imgList.filter(item => item.type == 0 || item.type == 3)
      const bottom = this.imgList.filter(item => item.type == 1)
      const others = this.imgList.filter(item => item.type == 2 || item.type == 4)
      const qty = [top.length, bottom.length, others.length]
      const topRes = this.initialRectangles(top, 0, qty)
      const bottomRes = this.initialRectangles(bottom, 1, qty)
      const othersRes = this.initialRectangles(others, 2, qty)
      if (topRes.length == 1 && bottomRes.length == 1) {
        topRes[0].x = 70
        bottomRes[0].x = 70
      }
      this.rectangles = [...topRes, ...bottomRes, ...othersRes]
    },
    initialRectangles(list, num, qty) {
      const result = list.map((item, index) => {
        const width = parseInt(item.width)
        const height = parseInt(item.height)
        const newItem = {
          src: item.imgUrl + this.zipImg50,
          rotation: 0,
          x: index * 150,
          y: 80,
          width: 200,
          height: (200 * height) / width,
          scaleX: 1,
          scaleY: 1,
          name: 'rect' + num + index,
          draggable: true
        }

        if (item.type == 0 || item.type == 3) {
          // 上装
          newItem.y = 70
        } else if (item.type == 1) {
          // 下装
          if (qty[0] > 0) {
            newItem.y = 70 + (170 * height) / width
          } else {
            newItem.y = 70
          }
          // 完全去除白边
          /*  newItem.width = 140
             newItem.height = 140 * height / width */
        } else if (item.type == 2 || item.type == 4) {
          // 通身
          newItem.width = 150
          newItem.height = (150 * height) / width
          newItem.x = index * 100
          if (qty[0] > 0 && qty[1] > 0) {
            newItem.y = 70 + (300 * height) / width
          } else if (qty[0] == 0 && qty[1] > 0) {
            newItem.y = 70 + (180 * height) / width
          } else if (qty[0] == 0 && qty[1] == 0) {
            newItem.y = 70
          }
        }
        if (num != 2) {
          if (list.length == 3) {
            newItem.x = index * 80
            if (index == 2) {
              newItem.x = 0
              newItem.y = 70 + (180 * height) / width
            }
          }
        }
        return newItem
      })
      return result
    },
    computeSize(url) {
      return new Promise((resolve, reject) => {
        var nImg = new Image()
        nImg.src = url
        var w, h
        nImg.onload = function () {
          w = nImg.width
          h = nImg.height
          resolve({
            width: w,
            height: h
          })
        }
      })
    },
    handleTransformEnd(e) {
      // shape is transformed, let us save new attrs back to the node
      // find element in our state
      const rect = this.rectangles.find(r => r.name === this.selectedShapeName)
      console.log(rect)
      // update the state
      rect.x = e.target.x()
      rect.y = e.target.y()
      rect.rotation = e.target.rotation()
      rect.scaleX = e.target.scaleX()
      rect.scaleY = e.target.scaleY()
    },
    handleStageMouseDown(e) {
      // clicked on stage - clear selection
      if (e.target === e.target.getStage()) {
        this.selectedShapeName = ''
        this.updateTransformer()
        return
      }

      // clicked on transformer - do nothing
      const clickedOnTransformer = e.target.getParent().className === 'Transformer'
      console.log(clickedOnTransformer)
      if (clickedOnTransformer) {
        return
      }

      // find clicked rect by its name
      const name = e.target.name()
      console.log(name)
      const rect = this.rectangles.find(r => r.name === name)
      console.log(rect)
      if (rect) {
        this.selectedShapeName = name
      } else {
        this.selectedShapeName = ''
      }
      this.updateTransformer()
      this.currentName = name
      // console.log(e.target.getStage().findOne('.' + this.selectedShapeName))
    },
    updateTransformer() {
      // here we need to manually attach or detach Transformer node
      const transformerNode = this.$refs.transformer.getNode()
      const stage = transformerNode.getStage()
      console.log(stage, 'xxxx')
      const { selectedShapeName } = this
      const selectedNode = stage.findOne('.' + selectedShapeName)
      //console.log(selectedNode)

      // do nothing if selected node is already attached
      if (selectedNode === transformerNode.node()) {
        return
      }

      if (selectedNode) {
        // attach to another node
        transformerNode.nodes([selectedNode])
      } else {
        // remove transformer
        transformerNode.nodes([])
      }
    },

    up() {
      console.log(this.currentName)
      const imgUp = this.$refs.stage.getStage().findOne('.' + this.currentName)
      imgUp.moveUp()
    },
    down() {
      console.log(this.currentName)
      const imgUp = this.$refs.stage.getStage().findOne('.' + this.currentName)
      imgUp.moveDown()
    },
    async save() {
      // clicked on stage - clear selection
      this.selectedShapeName = ''
      await this.updateTransformer()

      const stage = this.$refs.stage.getStage()
      console.log(this.$refs.stage.getStage())
      var dataURL = null

      dataURL = stage.toDataURL({
        pixelRatio: 2,
        quality: 1
        // mimeType:'image/jpeg'
      })

      if (dataURL != null && dataURL != '') {
        // alert(dataURL)
        //  this.baseImg = dataURL.toString()
        this.canvasImg = dataURL

        console.log(dataURL)
        const arr = this.createStylingList.map(item => item.id)
        console.log(arr)
        this.download(dataURL)
      } else {
      }
    },

    download(dataURL) {
      this.getUrlBase64(dataURL).then(base64 => {
        let elink = document.createElement('a')
        elink.href = base64
        const timedate = Date.parse(new Date())
        elink.download = `搭配图${timedate}.png`
        elink.click()
      })
    },

    getUrlBase64(url) {
      return new Promise(resolve => {
        let canvas = document.createElement('canvas')
        let ctx = canvas.getContext('2d')
        let img = new Image()
        img.crossOrigin = 'Anonymous' //允许跨域
        img.src = url
        img.onload = function () {
          let width = img.width //确保canvas的尺寸和图片一样
          let height = img.height
          canvas.width = width
          canvas.height = height
          let imageData = ctx.getImageData(0, 0, width, height)
          for (let i = 0; i < imageData.data.length; i += 4) {
            if (imageData.data[i + 3] == 0) {
              imageData.data[i] = 255
              imageData.data[i + 1] = 255
              imageData.data[i + 2] = 255
              imageData.data[i + 3] = 255
            }
          }
          ctx.putImageData(imageData, 0, 0)
          ctx.drawImage(img, 0, 0, width, height)
          let dataURL = canvas.toDataURL('image/png')
          canvas = null
          resolve(dataURL)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.konvajs-content {
  border: 1px dashed #dadada;
}
.img-content {
  display: flex;
  .left {
    flex: 1;
  }
  .right {
    margin-left: 20px;
  }
}
.footer-wrapper {
  margin-top: 20px;
}
</style>

